package cn.com.darly.vpm.mobile;

import cn.com.darly.vpm.business.BusinessApi;
import cn.com.darly.vpm.business.conversation.bean.ConversationMessage;
import cn.com.darly.vpm.framework.common.DateUtil;
import cn.com.darly.vpm.framework.common.StringDiyUtils;
import cn.com.darly.vpm.framework.common.UuidGenerateUtil;
import cn.com.darly.vpm.mobile.cfg.MobileBaseController;
import cn.com.darly.vpm.mobile.session.SessionUtil;
import cn.com.darly.vpm.security.securitycfg.SecurityApi;
import cn.com.darly.vpm.security.user.bean.User;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/** 登录用户发送消息
 * @author Darly/张宇辉/2018/5/21 13:46
 * @version 1.0/cn.com.darly.vpm.mobile
 */
@Controller
@RequestMapping("mobile/user/chat")
public class UserChaterController extends MobileBaseController {


    @Resource
    BusinessApi businessApi;

    @Resource
    SecurityApi securityApi;

    /**
     * 已登录用户相互发送消息，插入数据库信息。(获取我发送的消息，和我接收的消息)
     */
    @RequestMapping(value = {"/oldchatmsg"}, method = RequestMethod.POST)
    public void oldChatMsg(HttpServletRequest request, HttpServletResponse response){
        String  usertoken  = request.getHeader("usertoken");
        //收件人id
        String friendid = request.getParameter("friendid");
        //数据差异
        String messageinfoNub = request.getParameter("messageinfoNub");
        if (StringDiyUtils.isEmpty(usertoken)||StringDiyUtils.isEmpty(friendid)||StringDiyUtils.isEmpty(messageinfoNub)){
            simpleResult("201","参数缺失",request,response);
            return;
        }
        //获取用户登录信息
        User data = SessionUtil.SESSION_MAP.get(usertoken);
        if (data==null) {
            simpleResult("204","用户登录失效，请登录后重试",request,response);
            return;
        }
        //根据好友ID查询好友信息。
        User user =securityApi.findUserById(friendid);
        if (user == null){
            simpleResult("201","用户ID传递错误，请检查程序",request,response);
            return;
        }
        //查询消息
           List<ConversationMessage> msg =  businessApi.findChatMessage(data.getId(),friendid);
        if (msg!=null){
            if (msg.size()>Integer.parseInt(messageinfoNub)) {
                dataResult("200", "消息更新成功", msg.subList(Integer.parseInt(messageinfoNub),msg.size()), request, response);
            }else {
                simpleResult("201","没有可更新消息",request,response);
            }
        }else {
            simpleResult("201","消息更新失败",request,response);
        }
    }


    /**
     * 已登录用户相互发送消息，插入数据库信息。
     */
    @RequestMapping(value = {"/sendchatmsg"}, method = RequestMethod.POST)
    public void sendChatMsg(HttpServletRequest request, HttpServletResponse response){
        String browser =findBrowser(request);
        String  usertoken  = request.getHeader("usertoken");
        //内容
        String content = request.getParameter("content");
        //类型
        String type = request.getParameter("type");
        //收件人id
        String friendid = request.getParameter("friendid");
        if (StringDiyUtils.isEmpty(usertoken)||StringDiyUtils.isEmpty(content)||StringDiyUtils.isEmpty(type)||StringDiyUtils.isEmpty(friendid)){
            simpleResult("201","参数缺失",request,response);
            return;
        }
        //获取用户登录信息
        User data = SessionUtil.SESSION_MAP.get(usertoken);
        if (data==null) {
            simpleResult("204","用户登录失效，请登录后重试",request,response);
            return;
        }
        //根据好友ID查询好友信息。
        User user =securityApi.findUserById(friendid);
        if (user == null){
            simpleResult("201","用户ID传递错误，请检查程序",request,response);
            return;
        }



        ConversationMessage ms = new ConversationMessage();
        ms.setId(UuidGenerateUtil.getUUIDLong());
        ms.setMsgFrom(data.getId());
        ms.setMsgTo(friendid);
        ms.setMsgTime(DateUtil.now());
        ms.setMsgType(type);
        ms.setMsgContent(content);
        ms.setMsgOther("我发送给好友的消息");
        //插入消息数据库
        boolean saved = businessApi.saveConversationMsg(ms);
        ConversationMessage mesge = new ConversationMessage();
        mesge.setId(UuidGenerateUtil.getUUIDLong());
        mesge.setMsgFrom(friendid);
        mesge.setMsgTo(data.getId());
        mesge.setMsgTime(DateUtil.now());
        mesge.setMsgType("0");
        mesge.setMsgContent(content);
        mesge.setMsgOther("好友方接收到的消息");
        boolean show = businessApi.saveConversationMsg(mesge);
        if (saved&&show){
            //添加成功
            //调用Mqtt发送好友申請信息(是否可以推送一个JSON字符串过去)
            String json = JSON.toJSONString(ms);
            publishMessage("10#"+json+"#"+data.getId()+"#"+data.getName()+"#"+data.getDeptName()+"#",user.getDeviceId());
            saveLog(data.getId(),"0",0,3,data.getName(),browser,"[用戶："+data.getName()+"发送消息给"+user.getName()+"]");
            dataResult("200","消息发送成功",ms,request,response);
        }else {
            //添加失败
            simpleResult("201","消息发送失败",request,response);
        }
    }


}
